﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Lm.Common.Auth.Operation
{
    public abstract class OperationBase
    {
        private Model.Token token;
        public Model.Token Token { get { return this.token; } }

        protected OperationBase(string token)
        {
            this.token = this.ValidateToken(token);
        }

        /// <summary>
        /// 检查token和子类attribute，如果不通过验证，抛异常
        /// </summary>
        /// <param name="token"></param>
        private Model.Token ValidateToken(string token)
        {
            var attrList = this.GetType().GetCustomAttributes(typeof(OperationAttribute), false);
            if (attrList.Length != 1)
            { throw new Exception("当前类" + this.GetType().FullName + "没有OperationAttribute特性"); }
            var attr = (OperationAttribute)attrList.Single();
            using (var tran = new System.Transactions.TransactionScope())
            {
                var tokenModel = new Token.TokenValidator().Validate(token);
                new Role.ValidateRoleOperationPermission().Validate(tokenModel.OwnerAccount, tokenModel.OperatorAccount, attr.OprationId);
                if (
                        (tokenModel.ExpireTime - DateTime.Now)
                            <
                        TimeSpan.FromMinutes(Lm.Common.Auth.Config.ConfigReader.TokenExpireMinutes / 3)
                    )
                {
                    if (tokenModel.OwnerAccount == tokenModel.OperatorAccount)
                    {
                        new Token.DelayExpireTime().Delay(tokenModel.Id);
                    }
                }
                tran.Complete();
                return tokenModel;
            }
        }

        public static void CreateOperation(Type type)
        {
            var attrList = type.GetCustomAttributes(typeof(Operation.OperationAttribute), false);
            if (attrList.Length != 1)
            { throw new Exception("当前类" + type.FullName + "没有OperationAttribute特性"); }
            var dal = DAL.DALFactory.Create();
            var attr = (Operation.OperationAttribute)attrList.Single();
            using (var tran = new System.Transactions.TransactionScope())
            {
                if (dal.Exist<Model.Operation>(t => t.Id == attr.OprationId) == false)
                {
                    dal.Insert<Model.Operation>(new Model.Operation()
                    {
                        Id = attr.OprationId,
                        Name = attr.OperationName,
                        Pause = false,
                        Status = Model.OperationStatus.Live.ToString(),
                        Remark = attr.Remark,
                    });
                }
                tran.Complete();
            }
        }
    }
}
